<?php
include_once 'application/application.php';

class Page_vwgroups {

    private $table = 'views_group_list';

    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }




    function fieldRead(&$J) {
        $params = array();

        $_POST['id'] = Arr::getValue($_POST, 'vwg_id', 0);

        $params['action']       = $J->readVar('action');
        $params['id']           = (int)$J->readVar('id',0);
        $params['vwg_title']        = mysql_escape_string($J->readVar('vwg_title'));

        return $params;
    }


    public function checkFields($params) {
        $wrongFields = array();


        $name = 'vwg_title';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;




        return $wrongFields;

    }



    public function itemAdd() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->fieldRead($J);
        $wrongFields = $this->checkFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $q = "INSERT INTO `{$this->table}`
                           (`id`,   `title`                  )
                    VALUES (NULL,   '{$params['vwg_title']}' )";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_VWGROUP, $params);

        return $J;

    }

    public function itemUpdate() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->fieldRead($J);
        $wrongFields = $this->checkFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $all = getAllViewsGroups(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) return $J->error('Не удалось получить список групп <!--'.DB::getError().'-->');

        $old_val = Arr::getValue($all, $params['id'], false);
        if (!is_array($old_val)) return $J->error('Этот контакт не существует');




        $q = "UPDATE `{$this->table}`
              SET
                    `title` = '{$params['vwg_title']}',
              WHERE id = {$params['id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VWGROUP, array('old_value'=>$old_val, 'new_value'=>$params, 'id'=>$params['id']));

        return $J;

    }




    public function itemList() {
        //if ($this->error) $this->printOut ($this->error);

        $params = getAllViewsGroups(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) $this->error = 'Невозможно получить список контактов <!--'.DB::getError().'-->';


        $params['error'] = $this->error;

        echo includeFile(APP_PAGE_PARTS.'list_vwgroups.php', $params); // @todo группы
    }


    public function outPage() {
        $params = array();

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_vwgroups.php', $params));
    }




    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_vwgroups();

if ($page->action) {

    if ($page->action == ACTIONS::VIEW_ADD_GROUP)       echo $page->itemAdd();
    //if ($page->action == ACTIONS::CONTACT_UPDATE)       echo $page->contactUpdate();
}
else  {
    reLocate ('index.php'); /// !!!!!!!


    if (array_key_exists('getList', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->itemList();
    }
    else {
        if (!Auth::isLogged()) reLocate ('index.php');


        Navbar::$expanded = 'lm-manage-cnt';
        Navbar::$active = 'list_contacts';
        $page->outPage();
    }




}
?>